<?php
namespace app\service;
use think\facade\Db;
use app\model\ProductModel;
use Exception;

class ProductService{  
    public function list($params){
        $where=[];
        $page = $params['page'];
        $pageCount = $params['page_count'];
        if(!empty($params['typeid'])){
            $where[] = ['a.product_type_id','=',$params['typeid']];   
        }
        if(!empty($params['keyword'])){
            $where[] = ['a.product_name','like',"%{$params['keyword']}%"];   
        }
        $data = ProductModel::alias('a')->field('a.*,b.title as unit,c.name as product_type')->join('category b','a.unit_id=b.id')->join('product_type c','a.product_type_id=c.id')->where($where)->page($page,$pageCount)->order('a.id','desc')->select();         
        $count = ProductModel::alias('a')->where($where)->count(); 
        return ["list"=>$data,"count"=>$count];
    } 
    
    public function info($id){
        $products = ProductModel::where('id',$id)->select(); 
        return $products;
    }

    public function save($params){              
        if(empty($params['id'])){
            $data = ProductModel::where('product_name',$params['product_name'])->find();
            if($data){
                throw new Exception("商名称已存在");
            }
            $data = ProductModel::create($params); 
        }else{
            $data = ProductModel::update($params, ['id' => $params['id']]); 
        }        
        return $data;
    }

    public function delete($params){   
        $data = ProductModel::destroy($params['id']);         
        return $data;
    }
}